﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using WebApplication2.Model;
using WebApplication2.Server;
using WebApplication2.Util;

namespace WebApplication2.handler
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    public class Login : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string funC = context.Request.QueryString["funC"];
            try
            {
                switch (funC)
                {
                    case "Login":
                        EmpLogin(context);
                        break;

                    case "Logout":
                        EmpLogot(context);
                        break;
                }
            }
            catch (Exception e)
            {
                context.Response.ClearContent();
                context.Response.Write("{data:\"参数错误！\"}");
                context.Response.Write(e.ToString());
            }
        }

        /// <summary>
        /// 用户的登录处理程序
        /// </summary>
        /// context好像出了一些问题
        /// <param name="context"></param>
        public void EmpLogin(HttpContext context) 
        {
            string strData = "";
            string strType = "0";
            string empAccount = context.Request["empAccount"];
            string empPwd = DataBase.StringToMD5Hash(context.Request["pwd"]);//加密后的密码
            ///1.新建登录查询webService
            EmployeeInfo empInfo = EmployeeService.Instance.IsEmployeeExist(empAccount, empPwd);
            if (empInfo == null)
            {
                strType = "2";
                strData = "用户名或者密码错误";
                context.Response.Write("{Code:\"" + strType + "\",Msg:\"" + strData + "\"}");
                return;
            }
            //设置登录状态
            UsrAuth.SetLogin(context.Session, empInfo);
            ///直接使用cookie的方式来保存用户信息
            context.Response.Cookies["Account"].Value = empInfo.EmpAccount; //将值写入到客户端硬盘Cookie
            context.Response.Cookies["Account"].Expires = DateTime.Now.AddMinutes(60);//设置Cookie过期时间
            
            //登录状态cookie
            UsrAuth.SetLoginCookie(context.Response, empInfo.EmpAccount, empPwd);
            strType = "1";
            strData = "登录成功";
            context.Response.Write("{Code:\"" + strType + "\",Msg:\"" + strData + "\"}");
        }

        public void EmpLogot(HttpContext context)
        {
            UsrAuth.LoginOut(context.Session);
            UsrAuth.RemoveLoginCookie(context.Response);
            context.Response.Write("{Code:\"1\"}");
            context.Response.End();
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}